/**
 * 用户相关数据 - Pinia 组合式写法
 * @author rambler
 */
import {defineStore} from 'pinia'
import {ref, reactive, computed} from 'vue'

export const useUserStore = defineStore(
    'user',
    () => {
        // state
        const userInfo = reactive({
            id: '',
            nickname: '',
            avatar: '',
            username: '',
        })

        // actions
        function setUserInfo(payload: any) {
            const {username, id, avatar} = payload;
            userInfo.nickname = ''
            userInfo.avatar = avatar
            userInfo.username = username
            userInfo.id = id
        }

        function clearUserInfo() {
            userInfo.nickname = ''
            userInfo.avatar = ''
            userInfo.username = ''
            userInfo.id = ''
        }

        return {
            // 添加这一行，让 userInfo 成为 store 状态的一部分
            userInfo: userInfo,
            // getter
            id: computed(() => userInfo.id),
            nickname: computed(() => userInfo.nickname),
            avatar: computed(() => userInfo.avatar),
            username: computed(() => userInfo.username),

            // action
            setUserInfo,
            clearUserInfo,
        }
    },
    {
        // 持久化
        persist: {
            key: 'user',
            storage: localStorage
        },
    }
)
